/*************************************************
* Title：TinyToolKit
* Author：Opportunity 
* Describe：
* CreateTime：2020-08-14 16:58:26
* Version：1.0
* Modify Recorder：
*************************************************/

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

namespace TinyToolKit.Network
{
    public class Message
    {
        private byte[] buffer;
        private int buffCount;

        public byte[] Buffer => buffer;
        public int BuffCount => buffCount; 
        public int BuffRemain => buffer.Length - buffCount;

        public Message(int bufferSize = 1024)
        {
            buffer = new byte[bufferSize];
        }

        /// <summary>
        /// 解析数据
        /// </summary>
        /// <param name="amount">消息长度</param>
        /// <param name="callback">回调</param>
        public void ParseMessage(int amount,Action<byte[]> callback)
        {
            buffCount += amount;

            while (true)
            {
                if (buffCount <= sizeof(Int32)) break;
                
                //将字节数组buffer开始的4个字节转化为数据长度
                int dataLength = BitConverter.ToInt32(buffer, 0);
                if (buffCount - 4 >= dataLength)//判断当前数据是否完整
                {
                    byte[] tempData = new byte[dataLength];
                    Array.Copy(buffer, 4, tempData, 0, dataLength);
                    string msg = Encoding.UTF8.GetString(buffer, 4, dataLength);
                    buffCount -= 4 + dataLength;
                    Array.Copy(buffer, 4 + dataLength, buffer, 0, buffCount);
                    
                    callback?.Invoke(tempData);
                }
                else //当前数据不完整，不做数据处理，等待下次数据接收完整
                {
                    break;
                }
            }
        }

        public byte[] PackMessage(byte[] data)
        {
            byte[] lengthBytes = BitConverter.GetBytes(data.Length);
            return lengthBytes.Concat(data).ToArray();
        }
    }
}

